<?php

namespace App\Http\Controllers\Api;

use App\Models\BookCollection;
use App\Models\BookList;
use Illuminate\Http\Request;
use App\Http\Resources\BookList as BookListCollection;

class BookListController extends ApiController
{

    public function __construct()
    {
        $this->middleware('auth:api');
    }


    // 获取书单下的书籍
    public function index(BookCollection $collection){

        $book_list = $collection->bookList;

        return BookListCollection::collection($book_list);

    }



    // 加入书单
    public function store(BookCollection $collection,Request $request){

        $this->authorize('store',$collection);
        $this->validate($request,[
            'book_id' => 'required|exists:books,id',
            'remark' => 'required'

        ]);

        if ($collection->bookList()->where('book_id',$request->book_id)->exists()){
            return $this->failed('已加入,不能重新加入书单');
        }

        $collection->bookList()->create($request->all());

        return $this->message('添加成功');

    }


    // 删除书单
    public function destroy(BookCollection $collection,BookList $list){

        $this->authorize('destroy',$list);

        $list->delete();
        return $this->message('删除成功');

    }
}
